﻿using System;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Dimok {
  public class DataContextHelper : INotifyPropertyChanged{
    object value = "http://yahoo.com";

    public object Value {
      get { return this.value; }
      set { 
        this.value = value;
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Value"));
      }
    }



    public static string GetDataContextResource(DependencyObject obj) {
      return (string)obj.GetValue(DataContextResourceProperty);
    }

    public static void SetDataContextResource(DependencyObject obj, string value) {
      obj.SetValue(DataContextResourceProperty, value);
    }

    // Using a DependencyProperty as the backing store for DataContextResource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataContextResourceProperty =
        DependencyProperty.RegisterAttached("DataContextResource", typeof(string), typeof(DataContextHelper), new PropertyMetadata(null, DataContextResourcePropertyChangedCallback));


    static void DataContextResourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) {
      (d as FrameworkElement).DataContext = (Application.Current.Resources[e.NewValue] as DataContextHelper).Value;
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
  }
}
namespace Dimok.DataContext {
	public interface IDataContextChangedHandler<T> where T : FrameworkElement {
		void DataContextChanged(T sender, DependencyPropertyChangedEventArgs e);
	}
	public static class DataContextChangedHelper<T> where T : FrameworkElement, IDataContextChangedHandler<T> {
		private const string INTERNAL_CONTEXT = "InternalDataContext";

		public static readonly DependencyProperty InternalDataContextProperty =
				DependencyProperty.Register(INTERNAL_CONTEXT,
																		typeof(Object),
																		typeof(T),
																		new PropertyMetadata(_DataContextChanged));

		private static void _DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
			T control = (T)sender;
			control.DataContextChanged(control, e);
		}

		public static void Bind(T control) {
			control.SetBinding(InternalDataContextProperty, new Binding());
		}
	}
}